package com.sylar.happyreader.view;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;

public class AutoText extends View {
	private Paint mPaint = new Paint();
	private float fontSize;
	private int m_iFontHeight;
	private int marginWidth;
	private int marginHeight;
	private int mWidth;
	private int mHeight;
	private float scale;
	private int m_textColor = Color.BLACK;
	private int m_backColor = Color.WHITE;
	private List<String> m_lines = new ArrayList<String>();


	public AutoText(Context context) {
		this(context, null);
	}

	public void setText(List<String> lines) {
		this.m_lines = lines;
	}


	public AutoText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	public AutoText(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		init();
	}

	private void init() {

		scale = getContext().getResources().getDisplayMetrics().scaledDensity;
		mWidth = getContext().getResources().getDisplayMetrics().widthPixels;
		mHeight = getContext().getResources().getDisplayMetrics().heightPixels;

		marginWidth = (int) (20 * scale);
		marginHeight = (int) (20 * scale);
		fontSize = getRawSize(TypedValue.COMPLEX_UNIT_DIP, 20);

		mPaint.setAntiAlias(true);
		mPaint.setColor(m_textColor);
		mPaint.setStyle(Style.STROKE);
		mPaint.setTextSize(fontSize);
		FontMetrics fm = mPaint.getFontMetrics();
		m_iFontHeight = (int) Math.ceil(fm.descent - fm.top) + 4;
	}


	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);

		if (m_lines == null)
			return;

		canvas.drawColor(m_backColor);

		if (m_lines.size() > 0) {

			int mHeight = 0;
			for (String strLine : m_lines) {
				mHeight += m_iFontHeight;
				canvas.drawText(strLine, marginWidth, mHeight, mPaint);
			}
		}
	}

	public float getRawSize(int unit, float size) {
		Context c = getContext();
		Resources r;

		if (c == null)
			r = Resources.getSystem();
		else
			r = c.getResources();

		return TypedValue.applyDimension(unit, size, r.getDisplayMetrics());
	}


}